<template>
  <div class="user-manage">
    <div class="search-box">
      <div class="search-input">
        <van-cell-group>
          <van-field v-model="username" label="用户名" />
        </van-cell-group>
      </div>
      <div class="search-input">
        <van-cell-group>
          <van-field v-model="phoneNum" type="tel" label="手机号" />
        </van-cell-group>
      </div>
    </div>
    <div class="search-btn">
      <van-button icon="plus" type="info" @click="show = true">添加用户</van-button>
      <van-button icon="search" type="info">查询</van-button>
    </div>
    
    <div class="table">
      <div class="table-head">
        <van-grid column-num="5">
          <van-grid-item><div class="head-name">用户名</div></van-grid-item>
          <van-grid-item><div class="head-name">手机号码</div></van-grid-item>
          <van-grid-item><div class="head-name">地址</div></van-grid-item>
          <van-grid-item><div class="head-name">创建时间</div></van-grid-item>
          <van-grid-item><div class="head-name">操作</div></van-grid-item>
        </van-grid>
      </div>
      <div class="table-body">
        <van-grid column-num="5" v-for="(item, index) in list" :key="index">
          <van-grid-item>
            <div class="body-name">
              <input 
                type="text"
                v-model="item.username" 
                :disabled="item.onlyRead"
                :class="item.onlyRead ? '': 'add-border'"
                @input="changeUsername(index)">
            </div>
          </van-grid-item>
          <van-grid-item>
            <div class="body-name">
              <input 
                type="text"
                v-model="item.phoneNum" 
                :disabled="item.onlyRead"
                :class="item.onlyRead ? '': 'add-border'"
                @input="changePhoneNum(index)">
            </div>
          </van-grid-item>
          <van-grid-item>
            <div class="body-name">
              <input 
                type="text"
                v-model="item.address" 
                :disabled="item.onlyRead"
                :class="item.onlyRead ? '': 'add-border'"
                @input="changeAddress(index)">
            </div>
          </van-grid-item>
          <van-grid-item><div class="body-name">{{item.createTime}}</div></van-grid-item>
          <van-grid-item>
            <div class="body-btn">
              <button v-if="item.onlyRead" @click="handleUpdate(item._id, index)">修改</button>
              <button v-else @click="confrimUpdate(item._id, index)" style="background:#ee0a24 ;">确定</button>
              <button @click="handleDelete(item._id)">删除</button>
            </div>
          </van-grid-item>
        </van-grid>
      </div>
    </div>
    
    <!-- 添加用户 -->
    <van-overlay :show="show" @click="show = false">
      <div class="wrapper" @click.stop>
        <div class="block">
          <div class="close-btn" @click="show = false">
            <van-icon name="close" size="22px" />
          </div>
          <div class="content">
            <van-form @submit="onSubmit">
              <van-field
                v-model="form.username"
                name="username"
                label="用户名"
                placeholder="请输入用户名"
                required
                :rules="[{ required: true, message: '请填写用户名' }]"
              />
              <van-field
                v-model="form.password"
                type="password"
                name="password"
                label="密码"
                placeholder="请输入密码"
                required
                :rules="[{ required: true, message: '请填写密码' }]"
              />
              <van-field
                v-model="form.address"
                name="address"
                label="地址"
                placeholder="请输入地址"
              />
              <van-field
                v-model="form.phoneNum"
                required
                label="手机号"
                placeholder="请输入手机号"
                maxlength="11"
              />
              <div style="margin: 16px;">
                <van-button round block type="info" native-type="submit">添加</van-button>
              </div>
            </van-form>
          </div>
        </div>
      </div>
    </van-overlay>
    
  </div>
</template>

<script>
  import { Field, CellGroup, Grid, GridItem, Overlay, Form } from 'vant';
  export default {
    components: {
      [Field.name]: Field,
      [CellGroup.name]: CellGroup,
      [Grid.name]: Grid,
      [GridItem.name]: GridItem,
      [Overlay.name]: Overlay,
      [Form.name]: Form
    },
    data() {
      return {
        username: '',
        phoneNum: '',
        list: [],
        show: false,
        form: {
          username: '',
          password: '',
          address: '',
          phoneNum: ''
        },
        updateUsername: '',
        updatePhoneNum: '',
        updateAddress: '',
        doing: false  //true-正在修改某一条数据
      }
    },
    mounted() {
      this.getUserList()
    },
    
    methods: {
      
      //新增用户
      onSubmit(values) {
        if(this.form.phoneNum.length==0){
          this.$toast('手机号码不能为空')
          return
        }
        
        if(this.form.phoneNum.length < 11){
          this.$toast('请输入正确手机号码')
          return
        }
        
        const { username, password, address } = values
        const data = {
          username,
          password,
          address,
          phoneNum: this.form.phoneNum
        }
        this.$api.addUser(data).then(res => {
          this.$dialog.alert({
            title: '温馨提示',
            message: res.message
          })
          this.show = false
          this.getUserList()
          this.form = {
            username: '',
            password: '',
            address: '',
            phoneNum: ''
          }
        }).catch(err => {
          console.log('err', err)
          this.$dialog.alert({
            title: '温馨提示',
            message: err.error ? err.error : err
          })
        })
      },
      
      //查询用户列表
      getUserList() {
        this.$api.queryUserList().then(res => {
          this.list = this.formatTime(res.data) 
        }).catch(err => {
          console.log(err)
        })
      },
      
      //修改用户信息
      handleUpdate(id, index) {
        if(this.doing) {
          this.$dialog.alert({
            title: '温馨提示',
            message: `您当前正在修改中`
          })
        }else{
          this.doing = true
          this.list[index].onlyRead = false
        }
      },
      
      //确定修改用户信息
      confrimUpdate(id, index) {
        this.$dialog.confirm({
          title: '温馨提示',
          message: '您确定要修改吗？'
        }).then(() => {
          let userInfo = this.list[index]
          userInfo.username = this.updateUsername.length == 0 ? userInfo.username : this.updateUsername
          userInfo.phoneNum = this.updatePhoneNum.length == 0 ? userInfo.phoneNum : this.updatePhoneNum
          userInfo.address = this.updateAddress.length == 0 ? userInfo.address : this.updateAddress
          if(userInfo.username.length == 0){
            this.$dialog.alert({
              title: '温馨提示',
              message: '用户名不能为空'
            })
            return 
          }
          if(userInfo.phoneNum.length == 0){
            this.$dialog.alert({
              title: '温馨提示',
              message: '手机号码不能为空'
            })
            return
          }
          
          const data = {
            id,
            username: userInfo.username,
            phoneNum: userInfo.phoneNum,
            address: userInfo.address
          }
          console.log(data)
          this.$api.updateUser(data).then(res => {
            this.$dialog.alert({
              title: '温馨提示',
              message: res.message
            })
            this.getUserList()
          }).catch(err => {
            this.$dialog.alert({
              title: '温馨提示',
              message: err
            })
          })
          
        }).catch(() => {
          this.getUserList()
        })
        
        this.updateUsername = ''
        this.updatePhoneNum = ''
        this.updateAddress = ''
        this.doing = false
      },
      
      //监听input输入值
      changeUsername(index) {
        this.updateUsername = this.list[index].username
      },
      
      changePhoneNum(index) {
        this.updatePhoneNum = this.list[index].phoneNum
      },
      
      changeAddress(index) {
        this.updateAddress = this.list[index].address
      },
      
      //删除用户
      handleDelete(id) {
        this.$api.deleteUser({id}).then(res => {
          this.$dialog.alert({
            title: '温馨提示',
            message: res.message
          })
          this.getUserList()
        }).catch(err => {
          this.$dialog.alert({
            title: '温馨提示',
            message: err
          })
        })
      },
      
      formatTime(arr) { 
        let newArr = arr.map((item) => {
          let mydate = new Date(item.createTime)
          let year = mydate.getFullYear()
          let month = mydate.getMonth()+1
          let day = mydate.getDate()
          let hours = mydate.getHours()
          let min = mydate.getMinutes()
          let seconds = mydate.getSeconds()
          item.createTime = year+'-'+month+'-'+day+' '+hours+':'+min+':'+seconds
          item.onlyRead = true
          return item
        })
        return newArr
      },
      
      getCurrentTime() {
        let time = ''
        let mydate = new Date()
        let year = mydate.getFullYear()
        let month = mydate.getMonth()+1
        let day = mydate.getDate()
        let hours = mydate.getHours()
        let min = mydate.getMinutes()
        let seconds = mydate.getSeconds()
        time = year+'-'+month+'-'+day+' '+hours+':'+min+':'+seconds
        return time
      }
    }
  }
</script>

<style lang="scss" scoped>
  .user-manage {
    width: 100%;
    padding: 24px 5%;
    .search-box {
      display: flex;
      justify-content: space-between;
      .search-input {
        
      }
    }
    .search-btn {
      margin-top: 24px;
      display: flex;
    }
    .table {
      margin-top: 24px;
      .table-head {
        .head-name {
          color: #555;
          font-size: 14px;
          font-weight: 600;
          
        }
        ::v-deep .van-grid-item__content {
          background-color: #e7eaea;
        }
      }
      .table-body {
        .body-name {
          font-size: 14px;
          color: #666;
          input {
            width: 100%;
            text-align: center;
            padding: 2px 0;
            &.add-border{
              border: 1px solid #e8e8e8;
            }
          }
        }
        .body-btn {
          display: flex;
          justify-content: space-evenly;
          width: 100%;
          button {
            color: #fff;
            font-size: 12px;
            background: #1989fa;
            border-radius: 3px;
            padding: 4px 8px;
            cursor: pointer;
          }
        }
      }
    }
    
    .wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      .block {
        width: 520px;
        height: 360px;
        border-radius: 8px;
        padding: 0 30px;
        background-color: #fff;
        .close-btn {
          float: right;
          margin-top: 10px;
          margin-right: -20px;
        }
        .content {
          clear: right;
        }
      }
    }
  }
  ::v-deep .van-button {
    margin-right: 80px;
  }
</style>
